import {addCheckDate, initCheckDate, initDay} from "../../../network/per/signInPer";

export default {
    data() {
        return {
            worId:this.$store.state.loginUser.workId,
            currentDay: 1, // 当前天
            currentMonth: 1, // 当前月
            currentYear: 1970,
            currentWeek: 1, // 一号所在的星期
            days: [], // 当月所有天数
            content: {},
            arrDate: {
                // 天数集合
                checkInSet: [],
                // 状态集合
                statusSet: [],
            }, // 当月签到日期
            arrDateRequired: [], // 需要签到的日期
            // 签到验证规则
            checkinRule: [],
            num: 0,
            day: 10,
            sign: false,
        };
    },
    created() {
        this.init()
    },
    // mounted() {
    //
    // },
    methods: {
        async init(){
            await this.getSign();
            await this.getSignIn();
            this.initData()
        },
        /**
         * 获取签到日期
         */
        async getSignIn() {
            await initCheckDate(1001).then((das) => {
                if (das.code === 200) {
                    this.arrDate.checkInSet = []
                    this.arrDate.statusSet = das.data

                    for (let i = 0; i < das.data.length; i++) {
                        this.arrDate.checkInSet.push(parseInt(das.data[i].signDate.split("-")[2]))
                    }
                    console.log("获取签到日期 -> " ,this.arrDate.checkInSet)
                    this.initData(null);
                }
            })
        },

        /**
         * 获取需要签到的日期
         */
        async getSign() {
            await initDay(1001).then((das) => {
                if (das.code === 200) {
                    this.checkinRule = das.data
                    this.arrDateRequired = [];
                    let aa = das.data[0].rangeDays;
                    aa.forEach((a,b)=>{
                        let bt = a + "";
                        this.arrDateRequired.push(parseInt(bt.split("-")[2]));
                    })
                    console.log("获取需要签到的日期 -> ", this.arrDateRequired)
                    if (this.checkinRule.length === 0){
                        this.$toast.fail({message: '暂无排班'})

                    }
                }
            })
        },

        /**
         * 打印
         */
        initData(cur) {
            let date;
            if (cur) { // 切换日期
                date = new Date(cur);
            } else {
                var now = new Date();
                var d = new Date(this.formatDate(now.getFullYear(), now.getMonth() + 1, 1));
                d.setDate(35);// 设置天数为35天
                date = new Date(this.formatDate(d.getFullYear(), d.getMonth(), 1));
            }
            this.currentDay = date.getDate(); // 今日日期 几号
            this.currentYear = date.getFullYear(); // 当前年份
            this.currentMonth = date.getMonth() + 1; // 当前月份
            this.currentWeek = date.getDay(); // 0,1...6 星期

            const str = this.formatDate(this.currentYear, this.currentMonth, this.currentDay);
            this.days.length = 0; // 初始化日期
            // 如果今天是周日，放在第一行第7个位置，前面6个 这里默认显示一周，如果需要显示一个月，则第二个循环为 i<= 35- this.currentWeek
            for (var i = this.currentWeek; i > 0; i--) {
                const d = new Date(str);
                d.setDate(d.getDate() - i);
                var dayobject = {}; // 用一个对象包装Date对象  以便为以后预定功能添加属性
                dayobject.day = d;
                this.days.push(dayobject); // 将日期放入data 中的days数组 供页面渲染使用
            }
            // 其他周 // 设置天数为35天,周日设置在第一位，循环从36开始
            this.num = 0;
            for (var j = 0; j <= 36 - this.currentWeek; j++) {
                const d = new Date(str);
                d.setDate(d.getDate() + j);
                const cycleDate = d.getDate();
                if (cycleDate === 1) {
                    this.num++;
                }
                if (this.num === 2) {
                    return;
                }
                const dayobject = {
                    day: d,
                    isSign: this.isVerDate(cycleDate),
                    isStatus: this.checkInType(cycleDate),
                    commonly: this.isVerDate(cycleDate),
                };
                // console.log("dayobject ---> ",dayobject)
                // console.log("cycleDate ---> ",cycleDate)
                this.days.push(dayobject);
            }
        },


        /**
         * 判断 签到类型
         */
        checkInType(v) {
            if (this.isVerDate(v)){
                for (let i = 0; i < this.arrDate.statusSet.length; i++) {
                    if (parseInt(this.arrDate.statusSet[i].signDate.split("-")[2]) === v) {
                        if (this.arrDate.statusSet[i].statusList.indexOf(1) > 0) {
                            // 迟到
                            return 2;
                        }
                        // 缺勤
                        else if (this.arrDate.statusSet[i].statusList.indexOf(2) > -1){
                            console.log("缺勤")
                            return 4;
                        }
                        else if (this.arrDate.statusSet[i].statusList.indexOf(1) < 0) {
                            // 正常
                            return 1;
                        }
                        // 未打卡
                        else if (this.arrDate.statusSet[i].statusList.indexOf(1) === undefined) {
                            return 0;
                        }
                    }
                }
            }
            return false;
        },

        /**
         * 判断该日期是否有签到
         * @param v
         * @returns {boolean}
         */
        isVerDate(v) {
            let a = v + "";
            if (this.arrDateRequired.includes(Number(a.split(" ")))){
                return true;
            }
           return false
        },
        /**
         * 上一月
         * @param year
         * @param month
         */
        pickPre(year, month) {
            // const d = new Date(this.formatDate(year, month, 1));
            // d.setDate(0);
            // this.initData(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1));
            // initDay(1001, 1).then((das) => {
            //     this.arrDate.checkInSet = []
            //     let aa = das.data[0].rangeDays;
            //     for (const is in aa) {
            //         // console.log("isspit " , is.split("-")[2])
            //         this.arrDate.checkInSet.push(parseInt(is));
            //     }
            //     this.initData(null);
            // })
        },
        /**
         * 下一月
         * @param year
         * @param month
         */
        pickNext(year, month) {
            // const d = new Date(this.formatDate(year, month, 1));
            // d.setDate(35);
            // this.initData(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1));
            // initDay(1001, -1).then((das) => {
            //     let aa = das.data[0].rangeDays;
            //     aa.forEach((a,b)=>{
            //         let bt = a + "";
            //         this.arrDateRequired.push(parseInt(bt.split("-")[2]));
            //     })
            //     // for (const is in aa) {
            //     //     // console.log("isspit " , is.split("-")[2])
            //     //     this.arrDate.checkInSet.push(parseInt(is));
            //     // }
            //     this.initData(null);
            // })
        },

        // 返回 类似 yyyy-MM-dd 格式的字符串
        formatDate(year, month, day) {
            month < 10 && (month = '0' + month);
            day < 10 && (day = '0' + day);
            const data = year + '-' + month + '-' + day;
            return data;
        },
        /**
         * 点击签到
         * @param index
         */
        Sign() {
            const now = new Date()
            let year = now.getFullYear();
            let month = now.getMonth() + 1 + '';
            let day = now.getDate();
            let dayTime = now.toLocaleTimeString();

            if (month.length < 2) {
                month = '0' + month
            }

            let daydate = year + "-" + month + "-" + day;

            let aboolean = [];
            let sboolean = [];
            let xboolean = [];

            this.checkinRule.forEach((a, b) => {
                console.log(b +" ==== ")
                aboolean.push(this.checkinRule[b].rangeDays.indexOf(daydate) ? true : false)
                sboolean.push(this.compareTime(this.checkinRule[b].checkInAdvance,dayTime,this.checkinRule[b].checkDelayAdvance))
                xboolean.push(this.compareTime(this.checkinRule[b].signOutInAdvance,dayTime,this.checkinRule[b].signOutDelayAdvance))
            })

            sboolean.forEach((a,b)=>{
                let c = dayTime < this.checkinRule[b].checkDelayAdvance && aboolean[b] && sboolean[b] && xboolean[b]
                console.log("判断是否打卡", c)
                if (c) {
                    addCheckDate(1001,daydate,dayTime).then((das)=>{
                        if (das.code === 200){
                            this.$toast.success({
                                message: '签到成功！'
                            })
                            this.getSignIn();
                            this.sign = true;
                        }
                    })
                }
                if (!c){
                    this.$toast.fail({message: '未到打卡时间'})
                }
            })

        },

        /**
         * 判断时间是否在打卡范围中
         * @param startTime 开始时间
         * @param prepareTime 当前系统时间
         * @param endTime 结束时间
         * @returns {boolean} 符合0
         */
        compareTime(startTime,prepareTime ,endTime) {
            console.log(" spe " ,startTime,prepareTime,endTime)
            if (this.time_to_sec(startTime) <= this.time_to_sec(prepareTime) <= this.time_to_sec(endTime)) {
                return true;
            } else {
                return false;
            }

        },

        /**
         * 将时分秒转为时间戳
         * @param time 自定义时间
         * @returns {number}
         */
        time_to_sec(time) {
            if (time !== null) {
                // let start_time = startTime.replace(/-|\s|:|\//g, '');
                // let end_time = endTime.replace(/-|\s|:|\//g, '');
                let s = "";
                let hour = time.split(":")[0];
                let min = time.split(":")[1];
                let sec = time.split(":")[2];
                s = Number(hour * 3600) + Number(min * 60) + Number(sec);
                return s;
            }
        }
    }
}
